package servlet;

import pojo.Dept;
import service.DeptService;
import util.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// 此类可以响应web请求
// @ 注解
@WebServlet(urlPatterns = "/dept")
public class DeptServlet extends HttpServlet {

    // alt + insert


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 3行固定写法
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        DeptService deptService = new DeptService();

        String str_currentPage = req.getParameter("currentPage");
        // 将字符串类型的部门编号转换为整数类型
        int currentPage = 1;
        if (str_currentPage != null) {
            currentPage = Integer.parseInt(str_currentPage);
        }

        Page page = new Page();
        int totalCount = deptService.count();
        page.setTotalCount(totalCount);
        page.setCurrentPage(currentPage);
        page.setTotalPage();
        // 计算偏移量
        int offset = (currentPage - 1) * page.getPageSize();
        List<Dept> deptList = deptService.getDeptList(offset, page.getPageSize());
        // 存下来  session
        req.getSession().setAttribute("deptList",deptList);
        req.getSession().setAttribute("page",page);
        req.getSession().setAttribute("count",totalCount);
        // 转发到对应的页面显示数据
        req.getRequestDispatcher("deptindex.jsp").forward(req,resp);
    }
}
